package com.ming.common.dynamic.spring.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * @author moon
 * @date 2023-08-31 9:25
 * @since 1.8
 */
public class FileUtil {

    public static String readJson(String filePath){

        if (org.springframework.util.StringUtils.hasLength(filePath)){
            InputStream inputStream = null;
            StringBuilder builder = new StringBuilder();
            try {
                int batchSize = 2048;
                inputStream = new FileInputStream(filePath);
                byte[] temp = new byte[batchSize];
                int read;
                while ((read = inputStream.read(temp)) != -1){
                    if (read < batchSize){
                        byte[] tail = Arrays.copyOf(temp,read);
                        builder.append(new String(tail));
                    } else {
                        builder.append(new String(temp));
                    }
                }
                return builder.toString();
            } catch (IOException e) {
                return "";
            } finally {
                if (null != inputStream){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

        }
        return "";
    }


}
